import requests
import time
import random
from PIL import Image
from get_anti_content import get_anti_content, get_access_token
from image_signature import image_signature

cookies = {
    '_bee': 'j4sFD92EXhkNW1g6CBXTtVFhzZfFD0yO',
    '_f77': 'eff1e851-acec-4086-a75c-8103cb0a5907',
    '_a42': 'be292171-864e-45ac-a08b-68971f365e12',
    'rckk': 'j4sFD92EXhkNW1g6CBXTtVFhzZfFD0yO',
    'ru1k': 'eff1e851-acec-4086-a75c-8103cb0a5907',
    'ru2k': 'be292171-864e-45ac-a08b-68971f365e12',
    'api_uid': 'CiYY3mY83oxmEABoQxZcAg==',
}

headers = {
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
    'accesstoken': 'FFI246EXOUGFUKX25C3RGY7SEEHO3GMR6FIK7PVXPSBHMFBWRWJA1200774',
    'anti-content': '0asWfxUeM_VeBaijuoDqTU-S5f09RONxOrr5Va7tZF-fwEszoHL8pv-WV7kWpM-Rv4F-3qCI3RWS3ip6fRd7zY4uTYu3MI62obf623q_Ie7_OkBZ1eBk5D7xFmBsHIB35DB-MmMfZkMwsk9aaB65GHbUXRf-kMzZwazRmr3zkF3QeSL1SKB4ZHZwTTYqbOzngPv09Jy0tazV9fMfcets7eMMVIQ2wv3IWB1pALkfCIMxhkLxMetBcbWPmbRQVK3MAM14hL1qAS3MVHQBvE3hDSLZOeMWVeVI24uMfke-9SzyI9_vk4mMBXwv_ZZL-afkQCS7XmS1hpv2xuDk_-vjBvE1feBze7r1xkyVs_B_Zpgkh7k2F_BsPkv3hE6xRCFQHKvBp_Bz7kbsHhB1r5FRSZmd49IU2kPQBAB_ZHS_-Ke3jCFhUKL3wA7_4vr1coDHcdexUZjDo4S2_uemU9ReBP49X2DZ6uDsAmTn',
    # 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary80lN83IAsGNGd3tV',
    'origin': 'https://ktt.pinduoduo.com',
    'priority': 'u=1, i',
    'referer': 'https://ktt.pinduoduo.com/',
    'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
    # 'cookie': '_bee=j4sFD92EXhkNW1g6CBXTtVFhzZfFD0yO; _f77=eff1e851-acec-4086-a75c-8103cb0a5907; _a42=be292171-864e-45ac-a08b-68971f365e12; rckk=j4sFD92EXhkNW1g6CBXTtVFhzZfFD0yO; ru1k=eff1e851-acec-4086-a75c-8103cb0a5907; ru2k=be292171-864e-45ac-a08b-68971f365e12; api_uid=CiYY3mY83oxmEABoQxZcAg==',
}

def sleep_random():
    random_value = random.uniform(0.5, 1.5)
    print(f"等待{random_value:.2f}s ...")
    time.sleep(random_value)

def get_upload_sign():
    sign = image_signature()
    if 'signature' not in sign:
        print('image_signature failed', sign)
        raise SystemExit('签名获取失败')
            
    return sign['signature']

headers['accesstoken'] = get_access_token()

def image_info(image_url):
    headers['anti-content'] = get_anti_content()
    json_data = {
        'image_url': image_url,
        'sign': '34929A49ADEDFABAC6FAB09AC696390D',
        'signVersion': 'sv1',
        'timestamp': int(time.time() * 1000),
    }

    print('POST', 'https://api.pinduoduo.com/api/ktt_gateway/image/info')
    response = requests.post(
        'https://api.pinduoduo.com/api/ktt_gateway/image/info',
        cookies=cookies,
        headers=headers,
        json=json_data
    )
    if response.status_code == 200:
        print('image_info success', response.json())
        return response.json()['success']
    else:
        print('image_info failed', response.json())
        return None
    
def picture_check_base(image_url):
    headers['anti-content'] = get_anti_content()
    json_data = {
        'image_urls': [
            image_url,
        ],
        'route_type': 1,
        'safe_extend_params': {},
        'sign': 'A591CE663E8BCB19B0855702BA962B5F',
        'signVersion': 'sv1',
        'timestamp': int(time.time() * 1000),
    }

    print('POST', 'https://api.pinduoduo.com/api/ktt/safe/picture_check_base')
    response = requests.post(
        'https://api.pinduoduo.com/api/ktt/safe/picture_check_base',
        cookies=cookies,
        headers=headers,
        json=json_data
    )
    if response.status_code == 200:
        print('picture_check_base success', response.json())
        return ''
    else:
        print('picture_check_base failed', response.json())
        return None

def store_image(file_url):
    headers['anti-content'] = get_anti_content()
    # 获取图片文件宽和高
    with Image.open(file_url) as img:
        width, height = img.size
    
    crop = min(width, height, 1000)

    files = {
        'image': ('短裤4.jpg', open(file_url, 'rb'), 'image/jpeg'),
        'upload_sign': (None, get_upload_sign()),
        'pic_operations': (None, f'{{"rules":[{{"rule":"imageMogr2/crop/{crop}x{crop}/gravity/center","suffix":"suffix"}}],"original_needed":true}}'),
    }

    if crop < 500:
        files['pic_operations'] = (None, '{"rules":[{"rule":"imageMogr2/thumbnail/!500x500r|imageMogr2/crop/500x500/gravity/center","suffix":"suffix"}],"original_needed":true}')

    print('POST', 'https://file.pinduoduo.com/v3/store_image')
    response = requests.post(
        'https://file.pinduoduo.com/v3/store_image',
        cookies=cookies,
        headers=headers,
        files=files
    )
    if 'processed_urls' in response.json():
        print('store_image success', response.json())
        image_url = response.json()['processed_urls'][0]
        image_info(image_url)
        # picture_check_base(image_url)
        return image_url
    else:
        print('store_image failed', response.json())
        return ''
    
# for i in range(6):
#     print(f"{i}: {store_image('D:/春晓使用/01B马拉丁/'+'微信图片_20250503172939.jpg')}")
#     sleep_random()
